package com.heima.schedule.service.impl;

import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.schedule.service.TaskRefreshService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service
public class TaskRefreshServiceImpl implements TaskRefreshService {

    @Autowired
    private CacheService cacheService;

    /**
     * 异步刷新任务
     * @param futureKeySet
     */
    @Async("taskExecutor")
    @Override
    public void refreshTask(Set<String> futureKeySet) {
        for (String futureKey : futureKeySet) {
            //2.1 获取每个未来队列ZSet时间已到的任务集合
            Set<String> taskSet = cacheService.zRangeByScore(futureKey, 0, DateTime.now().getMillis());


            //2.2 使用Redis的Pipeline管道技术批量执行更新命令
            cacheService.getstringRedisTemplate().executePipelined(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    //1 从未来队列ZSet中删除任务集合
                    cacheService.zRemove(futureKey,taskSet);

                    //2 获取当前队列List的RedisKey
                    String topicRedisKey = futureKey.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);

                    //3 将任务集合添加到当前队列List中
                    cacheService.lLeftPushAll(topicRedisKey,taskSet);
                    return null;
                }
            });

        }
        log.info("[任务刷新]执行完毕");
    }
}
